package com.vert;

import com.vert.utils.ClazzScanUtils;
import com.vert.utils.FileWatcher;
import com.vert.utils.ObjectMaps;
import com.vert.utils.PropertiesUtils;
import io.vertx.core.*;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;

import java.util.List;


public class Application extends AbstractVerticle  {

  private static Class<?> clazz=null;


  public static void main(String[] args) throws Exception{
      Application.Run(Application.class);
  }

  public static void Run(Class<?> clazz){
    Vertx vertx = Vertx.vertx();
    Application.clazz=clazz;
    // 直接部署一个vertx程序
    vertx.deployVerticle(new Application());
  }

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    if(clazz == null){
        clazz=this.getClass();
    }

    Router router = Router.router(vertx);
    ClazzScanUtils.searchClass(Application.clazz);
    ClazzScanUtils.scanClass(Application.clazz);

    List<Class<?>> cls=ClazzScanUtils.getClassPaths();
    ObjectMaps.createClazzList(cls,router);


    router.route("/my/uploadimage/*")
      .handler(BodyHandler.create().setUploadsDirectory("mines").setBodyLimit(1000000000))
      .handler(StaticHandler.create().setWebRoot("mines").setCachingEnabled(false).setDirectoryListing(false));


    router.post("/my/uploadimage/").handler(ctx->{
      ctx.response().setChunked(true);


      for(FileUpload f : ctx.fileUploads()) {
        vertx.fileSystem().move(f.uploadedFileName(), "./mines/"+ f.fileName(), res->{
          if(res.succeeded()) {
            System.out.println("upload success.");
          } else {
            res.cause().printStackTrace();
          }
        });
      }
      ctx.response().end();
    });



    String port=PropertiesUtils.getProperty("port");

    vertx.createHttpServer()
      .requestHandler(router)
      .listen(Integer.parseInt(port))
      .onSuccess(server ->
        System.out.println(
          "HTTP server started on port " + server.actualPort()
        )
      );

    FileWatcher.init();
  }



}
